package com.cuihaodong.controller;
/**
 * eureka服务端,进行服务的注册/剔除/更新等
 * @author cuihaodong
 */

import com.alibaba.fastjson.JSON;
import com.cuihaodong.pojo.InstanceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


@RestController
@RequestMapping("/eurekaServer")
public class EurekaServerController {

    @Autowired
    private RedisTemplate redisTemplate;

    private final String serverKey = "service";

    /**
     * 注册服务
     * @param instanceInfo
     */
    @RequestMapping("/registerService")
    public String registerService(@RequestBody InstanceInfo instanceInfo){

        System.out.println(instanceInfo);
        String applicationName = instanceInfo.getApplicationName();

        //从redis中通过applicationName查询服务
        String result = (String)redisTemplate.boundHashOps(serverKey).get(applicationName);

        if(result == null || "".equals(result) || result.length()==0){
            //redis中没有此服务,将服务存入redis中
            List<InstanceInfo> list = new ArrayList<>();
            list.add(instanceInfo);
            //将list转为json
            String jsonData = JSON.toJSONString(list);
            redisTemplate.boundHashOps(serverKey).put(applicationName,jsonData);
        } else {
            //将从redis中获取的数据转换为list
            List<InstanceInfo> redisList = JSON.parseArray(result, InstanceInfo.class);
            for (InstanceInfo info : redisList) {
                if(info.getIp().equals(instanceInfo.getIp()) && info.getPort().equals(instanceInfo.getPort())){
                    //有重复服务.将原有的服务删除
                    redisList.remove(info);
                    break;
                }
            }
            //没有重复的服务,则将这个服务直接添加到集合中
            redisList.add(instanceInfo);
            //删除原先的服务
            redisTemplate.boundHashOps(serverKey).delete(applicationName);
            //将redisList转为json
            String redisListJson = JSON.toJSONString(redisList);
            redisTemplate.boundHashOps(serverKey).put(applicationName,redisListJson);
        }
        return "注册成功";
    }

    /**
     * 根据appName获取
     * @return
     */
    @RequestMapping("/pullServices")
    public Map<String,InstanceInfo> pullServices(){
        Map entries = redisTemplate.boundHashOps(serverKey).entries();
        System.out.println(entries);
        return entries;
    }

    @RequestMapping("/updateService")
    public String updateService(@RequestBody InstanceInfo instanceInfo){
        //通过ip查询注册的服务,
        String json = (String) redisTemplate.boundHashOps(serverKey).get(instanceInfo.getApplicationName());
        //将查询到的json数据转换为集合
        List<InstanceInfo> infoList = JSON.parseArray(json, InstanceInfo.class);
        for (InstanceInfo info : infoList) {
            if(info.getIp().equals(instanceInfo.getIp()) && info.getPort().equals(instanceInfo.getPort())){
                //如果存在此服务,更新时间戳
                info.setRegisterDate(new Date());
                return "更新成功";
            }
        }
        return "没有ip为:"+instanceInfo.getIp()+"端口为:"+instanceInfo.getPort()+"的服务,请重新注册";
    }

    @Scheduled(cron = "*/2 * * * * ?")
    public void removeService(){
        Map entries = redisTemplate.boundHashOps(serverKey).entries();
        System.out.println("entries:"+entries);

        //keySet为applicationName的集合
        Set<String> keySet = entries.keySet();

        for (String applicationName : keySet) {
            //applicationName为s的服务的集合的json形式
            String json = (String) entries.get(applicationName);
            //将json转为list集合
            List<InstanceInfo> list = JSON.parseArray(json, InstanceInfo.class);
            if(list.size() == 0 || list == null) {
                System.out.println("applicationName为:"+applicationName+"的服务都已经过期");
                //如果applicationName对应的list为空,则删除
                redisTemplate.boundHashOps(serverKey).delete(applicationName);
            } else{
                for (int i = 0;i<list.size();i++) {
                    Long time = System.currentTimeMillis()-list.get(i).getRegisterDate().getTime();
                    if(time > 90000){
                        System.out.println(list.get(i).getApplicationName()+"这个应用名的ip为:"+list.get(i).getIp()+"的服务已经超过90s没有发送心跳了");
                        list.remove(i);
                    }
                    //将剔除服务后的list转换为json存入redis中
                    if(list.size()<=0 || list == null){
                        redisTemplate.boundHashOps(serverKey).delete(applicationName);
                        break;
                    }
                    String result = JSON.toJSONString(list);
                    redisTemplate.boundHashOps(serverKey).put(list.get(i).getApplicationName(),result);
                }
            }
        }
    }
}
